//
//  HouseListViewController.m
//  sellHouse
//
//  Created by 李 佳伟 on 2018/11/23.
//  Copyright © 2018年 李 佳伟. All rights reserved.
//

#import "HouseListViewController.h"
#import "JTCSM.h"
#import "housListTableViewCell.h"
#import "MJRefresh.h"
@interface HouseListViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSInteger currentPage;
    NSInteger totalcurrentPage;
}
@property (nonatomic,strong) UITableView *tableview;
@property (nonatomic,strong) NSMutableArray *dynamicList;
@end

@implementation HouseListViewController


#pragma mark 页面返回
- (void)gotoback{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    currentPage=0;
    leftBarButtonItems_rightBarButtonItems *leftbtn = KCUSTOMNAVIGSTION_ALLOC;
   self.navigationItem.leftBarButtonItem= [leftbtn setBarButtonItemsImageName:@"erweimafanhui.png" frame:KLeftBarButtonItemFrame_image target:self SEL:@selector(gotoback)];
    self.dynamicList = [NSMutableArray array];
    [df isRemoveTarbar:YES];
    _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KCONTROLLERWith, KSCREENHeight) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.separatorStyle = UITableViewCellSelectionStyleNone;
    _tableview.backgroundColor = RGBACOLOR(246, 246, 246, 1);
    [self.view addSubview:_tableview];
    
   
     __block HouseListViewController *myself = self;
    // 下拉刷新
    _tableview.mj_header= [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [myself setRequest];
        });
    }];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    _tableview.mj_header.automaticallyChangeAlpha = YES;
    
    // 上拉刷新
    _tableview.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
         if (self->currentPage < self->totalcurrentPage) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
           
                myself->currentPage++;
                [myself setMoreRequest];
           
            
        });
         }else{
            [myself.tableview.mj_footer endRefreshingWithNoMoreData];
         }
    }];
    
     [self setRequest];
    // Do any additional setup after loading the view.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (currentPage >=totalcurrentPage && currentPage >0  && self.dynamicList.count>0 ) {
        return self.dynamicList.count+1;
    }
    return self.dynamicList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *cellid = [NSString stringWithFormat:@"%ld-%ld",indexPath.section,indexPath.row];
    if (indexPath.row == self.dynamicList.count  && self.dynamicList.count>0) {
        
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (cell== nil) {
            cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
            UILabel *label = [UILabel initWithFrame:CGRectMake(0, 0, KSCREENWidth, 50) text:@"没有更多了" font:15 textAlignment:NSTextAlignmentCenter texcolor:RGBACOLOR(151, 151, 151, 1) backgroundColor:RGBACOLOR(246, 246, 246, 1)];
            [cell.contentView addSubview:label];
            cell.backgroundColor =RGBACOLOR(246, 246, 246, 1);
        }
        return cell;
        
    }else{
        housListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (cell==nil) {
            cell = [[housListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellid];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row>=self.dynamicList.count || indexPath==nil) {
            return cell;
        }
        HouserInfoModel *model = self.dynamicList[indexPath.row];
        [cell setvalueWithModel:model];
        if (model.Newid == self.house_id) {
            cell.touchImagev.hidden = NO;
        }
        
        return cell;
    }
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == self.dynamicList.count) {
        return 100;
    }
    return cellHeight;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row>=self.dynamicList.count || indexPath==nil) {
        return ;
    }
    HouserInfoModel *model = [self.dynamicList objectAtIndex:indexPath.row];
    [self.delegate rebackRequestWithHouse_id:model];
    [self.navigationController popViewControllerAnimated:YES];
    
}

#pragma mark 网络请求
- (void)setRequest{
    [self.dynamicList removeAllObjects];
    self.dynamicList = nil;
    self.dynamicList = [NSMutableArray array];
    __block HouseListViewController *myself = self;
    currentPage = 1;
    [[LoadData object] loadDataPostAsynchronousWithURL:@"hkapp/saleHouse/getSaleHouseForPage" withDict:@{@"currentPage":[NSString stringWithFormat:@"%ld",(long)currentPage] ,@"rowCount":@"10",@"token":KTokenString,@"isSupper":@"",@"phone":KHkTellString} superView:nil Block:^(id  _Nullable responseObject) {
        NSArray *list =[KResponseData objectForKey:@"pagerResults"];
        if(list == nil || list.count<=0){
            [df getImageView:myself.tableview isbigImaga:@"datanull.jpg" Target:myself action:nil];
        }else{
            [df removeImageView:myself.tableview];
        }
        for (int i = 0; i<list.count; i++) {
            HouserInfoModel *model = [[HouserInfoModel alloc]init];
            [model setValuesForKeysWithDictionary:list[i]];
            [myself.dynamicList addObject:model];
        }
       
        myself->totalcurrentPage = [[KResponseData objectForKey:@"pageCount"] integerValue];
        [myself.tableview reloadData];
        
        [myself.tableview.mj_header endRefreshing];
        [myself.tableview.mj_footer resetNoMoreData];
    
     
    }];
}

- (void)setMoreRequest{
    __block HouseListViewController *myself = self;
    [[LoadData object] loadDataPostAsynchronousWithURL:@"hkapp/saleHouse/getSaleHouseForPage" withDict:@{@"currentPage":[NSString stringWithFormat:@"%ld",(long)currentPage] ,@"rowCount":@"10",@"token":KTokenString,@"isSupper":@"",@"phone":KHkTellString} superView:nil Block:^(id  _Nullable responseObject) {
        NSArray *list =[KResponseData objectForKey:@"pagerResults"];
        myself->totalcurrentPage = [[KResponseData objectForKey:@"pageCount"] integerValue];
            for (int i = 0; i<list.count; i++) {
                HouserInfoModel *model = [[HouserInfoModel alloc]init];
                [model setValuesForKeysWithDictionary:list[i]];
                [myself.dynamicList addObject:model];
            }
            [myself.tableview reloadData];
            // 结束刷新
        
            [myself.tableview.mj_footer endRefreshing];
    
        
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
